package com.aganmall.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by GJY on 17/5/14.
 */
public class TokenCache {
    //logback中的日志,通过工厂接口的class装载调用
    private static Logger logger = LoggerFactory.getLogger(TokenCache.class);

    //将token_前缀做成常量方便调用
    public static final String TOKEN_PREFIX = "token_";

    //Guava中的local cache,通过调用链模式调用,并设置缓存的初始化容量为1000,最大容量10000,最大保留时间
    //超出10000则使用:LRU算法(最少使用算法)
    private static LoadingCache<String, String> localCache = CacheBuilder.newBuilder().initialCapacity(1000)
            .maximumSize(10000).expireAfterAccess(12, TimeUnit.HOURS)
            .build(new CacheLoader<String, String>() {
                //默认的数据加载实现,当调用get方法取值时,若key没有对应的值,就调用这个方法进行加载
                @Override
                public String load(String s) throws Exception {
                    return "null";
                }
            });

    //外部调用来setKey,getKey
    public static void setKey(String key, String value){
        localCache.put(key,value);
    }

    public static String getKey(String key){
        String value = null; //初始化一个value
        try {
            value = localCache.get(key);
            if ("null".equals(value)){
                return null;
            }
            return value;
        }catch (Exception e){
            logger.error("local cache get error",e);
        }
        return null;
    }

}
